Macroable
Extend class
prototype in style 😎
Macroable is a simple class that your classes can extend in order to expose an API for extending the class. Let's see how a class can be extended without Macroable first.
Traditional approach
class Foo {}
module.exports = Foo
Someone can extend it follows.
const Foo = require('./Foo')
Foo.prototype.greet = function () {
return 'Hello!'
}
Object.defineProperty(Foo.prototype, 'username', {
get: function () {
return 'virk'
}
})
Using macroable it's simpler
const { Macroable } from 'macroable'
class Foo extends Macroable {
}
Foo._macros = {}
Foo._getters = {}
module.exports = Foo
const Foo = require('./Foo')
Foo.macro('greet', function () {
return 'Hello!'
})
Foo.getter('username', function () {
return 'virk'
})
You can see the API is simpler and less verbose. However, their are couple more benefits to using Macroable.
- You can add singleton getters, which are evaluated only once and then cached value is returned.
- Cleanup all
macros
and getters
added using Macroable.
Installation
npm i macroable
Usage
const { Macroable } from 'macroable'
class Foo extends Macroable {
}
Foo._macros = {}
Foo._getters = {}
module.exports = Foo
API
macro(name, callback) => void
Add a function to the prototype
Foo.macro('greet', function (name) {
return `Hello ${name}!`
})
hasMacro(name) => boolean
Find if macro exists.
Foo.hasMacro('greet')
getter(name, callback, isSingleton?) => void
Add getter to the prototype and optionally make it singleton.
Foo.getter('username', function () {
return 'virk'
}, true)
hasGetter(name) => boolean
Find if getter exists.
Foo.hasGetter('greet')
hydrate
Remove all macros and getters added using Macroable
.
Foo.getter('username', function () {
return 'virk'
}, true)
Foo.hydrate()
Foo.hasGetter('username')
Change log
The change log can be found in the CHANGELOG.md file.
Contributing
Everyone is welcome to contribute. Please go through the following guides, before getting started.
- Contributing
- Code of conduct
Authors & License
thetutlage and contributors.
MIT License, see the included MIT file.